import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/',
        component: () => import('@/views/HomePage.vue'),
        redirect: '/dashboard',
        meta: { requiresAuth: true }, // 添加这个meta字段
        children: [
            {
                path: 'dashboard',
                component: () => import('@/views/DashboardPage.vue'),
                meta: { title: '数据看板' }
            },
            {
                path: 'adminList',
                component: () => import('@/views/AdminListPage.vue'),
                meta: { title: '管理员管理' }
            },
            {
                path: 'userList',
                component: () => import('@/views/UserListPage.vue'),
                meta: { title: '用户管理' }
            },
            {
                path: 'carList',
                component: () => import('@/views/CarListPage.vue'),
                meta: { title: '爱车管理' }
            },
            {
                path: 'recordList',
                component: () => import('@/views/RecordListPage.vue'),
                meta: { title: '油耗管理' }
            },
        ]
    },
    {
        path: '/login',
        component: () => import('@/views/LoginPage.vue'),
        meta: { title: '登录' }
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token')

    // 如果路由需要认证但用户未登录
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
        return
    }
    // 如果用户已登录但尝试访问guestOnly页面(如登录页)
    if (to.meta.guestOnly && isAuthenticated) {
        next('/') // 重定向到首页
        return
    }
    next() // 正常放行
})

export default router